package com.jdk.learn.juc2.thread.excrise;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 类功能描述:
 *    内存屏障
 * @author bgt
 * @version V1.0
 * @since 2019-02-27 10:01
 */
public class CyclicBarrierDemo {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(() -> {
            try {
                System.out.println(Thread.currentThread().getName()+" step  A");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName()+" step  B");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName()+" step  C");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        });
        executorService.submit(() -> {
            try {
                System.out.println(Thread.currentThread().getName()+" step  A");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName()+" step  B");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName()+" step  C");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        executorService.shutdown();
    }
}
